#!/bin/bash

# P2P Boot Tool (PBT), by Gabriel Winckler (C) 2009

#	This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

# This software has the influence of Clusters for Everyone, by Cicuttin Matteo,
#	a evolution of Hopeless by Christian Pellegrin

# Usage: [DIR] [METALINK_URL]

# dir: directory were files will be downloaded
# metalink_url: optional, the metalink url. If not presented, try to use kopt metalink

check_new_image()
{

	echo check image $METALINK

	aria2c --follow-metalink=false -d $DIR -o $FILE.new $METALINK

	if ! $(diff $DIR/$FILE $DIR/$FILE.new)
	then
		mv $DIR/$FILE.new $DIR/$FILE
		return 0
	else
		rm $DIR/$FILE.new
		return 1
	fi
}

download()
{
	echo download
	aria2c -d $DIR --seed-time=0 $METALINK 
}

change_image()
{
	echo change image
	
	mkdir -p $MOUNT_DIR/$IMAGE
	mount -o loop -t squashfs $DIR/$IMAGE $MOUNT_DIR/$IMAGE
	mount -o remount,add:1:$MOUNT_DIR/$IMAGE /

	for i in $(ls $MOUNT_DIR/*.squashfs)
	do
		if [ $i != $IMAGE ]
		then
			if [ $(mount -o remount,del:$MOUNT_DIR/$i /) ]
			then
				echo Trying to remove $i mountpoint
				umount $MOUNT_DIR/$i
				rmdir $MOUNT_DIR/$i
				# TODO: remove the old image
			fi
		fi
	done
}

DIR=$1
MOUNT_DIR=/boot/pbt/

if test $2
then
	METALINK=$2
else
	METALINK=$(cat /proc/cmdline | sed "s/.*metalink=\([^ ]*\).*/\1/")
fi



if check_new_image
then
	IMAGE=$(aria2c -S $DIR/$FILE | grep '  1' | cut -d '|' -f 2)
	download
	change_image
fi
